package com.badminton.web.config;

import com.alibaba.fastjson.JSON;
import com.badminton.web.exception.BusinessException;
import com.badminton.web.model.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：chens9
 * @date ：2021-10-14 17:23
 * @email ：chens9@qq.com
 * @description 全局异常统一处理，如果想对异常在做区分，可对e进行详细异常判断
 */
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {
    @ExceptionHandler(value = Exception.class)
    public BaseResponse errorHandler(HttpServletRequest request, Exception e){
        String url = request.getRequestURI();
        String ip = request.getRemoteAddr();
        log.error("io>exception[]"+" > "+ip+"请求"+url+" error: ", e);
        BaseResponse result = BaseResponse.fail(e.getMessage());
        //判断异常类型
        if (e instanceof BusinessException) {
            result.setCode(444);
        }

        log.info("io>result[]"+" > "+ip+"请求"+url+" output: "+ JSON.toJSONString(result));
        return result;
    }
}
